<?php
// 安装页面 - 包含使用条款和数据库连接设置

session_start();

// 引入语言类
require_once 'Language.php';

// 初始化语言类，默认日语
$language = new Language();

// 定义安装状态常量
define('INSTALLATION_STEP', [
    'TERMS' => 1,
    'DB_CONFIG' => 2,
    'INSTALL' => 3,
    'COMPLETE' => 4
]);

// 初始化安装步骤
if (!isset($_SESSION['install_step'])) {
    $_SESSION['install_step'] = INSTALLATION_STEP['TERMS'];
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    switch ($_SESSION['install_step']) {
        case INSTALLATION_STEP['TERMS']:
            if (isset($_POST['agree_terms'])) {
                $_SESSION['install_step'] = INSTALLATION_STEP['DB_CONFIG'];
            }
            break;
        
        case INSTALLATION_STEP['DB_CONFIG']:
            // 验证数据库连接信息
            $db_host = $_POST['db_host'] ?? '';
            $db_name = $_POST['db_name'] ?? '';
            $db_user = $_POST['db_user'] ?? '';
            $db_pass = $_POST['db_pass'] ?? '';
            $db_port = $_POST['db_port'] ?? '3306';
            
            // 尝试连接数据库
            try {
                $pdo = new PDO(
                    "mysql:host=$db_host;port=$db_port;dbname=$db_name;charset=utf8mb4",
                    $db_user,
                    $db_pass,
                    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
                );
                
                // 保存数据库配置
                $_SESSION['db_config'] = [
                    'host' => $db_host,
                    'name' => $db_name,
                    'user' => $db_user,
                    'pass' => $db_pass,
                    'port' => $db_port
                ];
                
                $_SESSION['install_step'] = INSTALLATION_STEP['INSTALL'];
            } catch(PDOException $e) {
                $error = '数据库连接失败: ' . $e->getMessage();
            }
            break;
        
        case INSTALLATION_STEP['INSTALL']:
            // 执行安装
            try {
                $db_config = $_SESSION['db_config'];
                
                // 连接数据库
                $pdo = new PDO(
                    "mysql:host={$db_config['host']};port={$db_config['port']};dbname={$db_config['name']};charset=utf8mb4",
                    $db_config['user'],
                    $db_config['pass'],
                    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
                );
                
                // 创建工单表
                $sql = "CREATE TABLE IF NOT EXISTS tickets (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    qq_number VARCHAR(20) NOT NULL,
                    feedback_type VARCHAR(50) NOT NULL,
                    severity INT NOT NULL,
                    description TEXT NOT NULL,
                    screenshots TEXT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
                $pdo->exec($sql);
                
                // 创建管理员表
                $sql = "CREATE TABLE IF NOT EXISTS admins (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    username VARCHAR(50) NOT NULL UNIQUE,
                    password VARCHAR(255) NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
                $pdo->exec($sql);
                
                // 创建SMTP设置表
                $sql = "CREATE TABLE IF NOT EXISTS smtp_settings (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    host VARCHAR(100) NOT NULL,
                    port INT NOT NULL,
                    username VARCHAR(100) NOT NULL,
                    password VARCHAR(255) NOT NULL,
                    encryption VARCHAR(10) DEFAULT NULL,
                    from_email VARCHAR(100) NOT NULL,
                    from_name VARCHAR(100) NOT NULL,
                    notification_email VARCHAR(100) DEFAULT NULL,
                    notification_enabled BOOLEAN DEFAULT FALSE,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
                $pdo->exec($sql);
                
                // 插入默认管理员账户
                $passwordHash = password_hash('admin123', PASSWORD_DEFAULT);
                $sql = "INSERT IGNORE INTO admins (username, password) VALUES ('admin', :password)";
                $stmt = $pdo->prepare($sql);
                $stmt->bindParam(':password', $passwordHash);
                $stmt->execute();
                
                // 插入默认SMTP设置
                $sql = "INSERT IGNORE INTO smtp_settings (host, port, username, password, encryption, from_email, from_name) 
                        VALUES ('smtp.qq.com', 465, 'your_email@qq.com', 'your_authorization_code', 'ssl', 'your_email@qq.com', '工单系统')";
                $pdo->exec($sql);
                
                // 更新配置文件
                $config_content = "<?php
// 数据库配置
define('DB_HOST', '{$db_config['host']}');
define('DB_NAME', '{$db_config['name']}');
define('DB_USER', '{$db_config['user']}');
define('DB_PASS', '{$db_config['pass']}');
define('DB_PORT', '{$db_config['port']}');

// 应用配置
define('APP_NAME', '异次元工单管理系统');
define('APP_URL', 'http://' . \$_SERVER['HTTP_HOST']);

try {
    // 创建PDO实例
    \$pdo = new PDO(
        'mysql:host=' . DB_HOST . ';port=' . DB_PORT . ';dbname=' . DB_NAME . ';charset=utf8mb4',
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false
        ]
    );
} catch(PDOException \$e) {
    die('数据库连接失败: ' . \$e->getMessage());
}
?>";
                
                file_put_contents('../config.php', $config_content);
                
                $_SESSION['install_step'] = INSTALLATION_STEP['COMPLETE'];
            } catch(PDOException $e) {
                $error = '安装失败: ' . $e->getMessage();
            } catch(Exception $e) {
                $error = '系统错误: ' . $e->getMessage();
            }
            break;
    }
}

// 如果已完成安装，重定向到登录页面
if ($_SESSION['install_step'] === INSTALLATION_STEP['COMPLETE'] && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../admin/index.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $language->get('title'); ?></title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=ZCOOL+KuaiLe&family=Ma+Shan+Zheng&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #ff6b8b;
            --secondary: #74b9ff;
            --accent: #55efc4;
            --background: #f9f9f9;
            --text: #333;
            --light-text: #777;
            --border: #ddd;
            --card-bg: #fff;
            --success: #2ecc71;
            --error: #e74c3c;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'ZCOOL KuaiLe', cursive, sans-serif;
            background-color: var(--background);
            color: var(--text);
            line-height: 1.6;
            background-image: url('../admin/admin.webp'), url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><circle cx="50" cy="50" r="2" fill="%23ff6b8b" opacity="0.2"/></svg>');
            background-size: cover, auto;
            background-position: center, center;
            background-repeat: no-repeat, repeat;
            background-attachment: fixed;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px 0;
            background-color: var(--card-bg);
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            position: relative;
            overflow: hidden;
        }
        
        .header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 5px;
            background: linear-gradient(90deg, var(--primary), var(--secondary), var(--accent));
        }
        
        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            color: var(--primary);
            text-shadow: 2px 2px 0 rgba(0,0,0,0.1);
            font-family: 'Ma Shan Zheng', cursive;
        }
        
        .header p {
            color: var(--light-text);
            font-size: 1.1rem;
        }
        
        .install-card {
            background-color: var(--card-bg);
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            padding: 30px;
            margin-bottom: 30px;
            position: relative;
            overflow: hidden;
        }
        
        .install-card::after {
            content: '';
            position: absolute;
            bottom: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23ff6b8b" opacity="0.1"><path d="M12,2C6.48,2,2,6.48,2,12s4.48,10,10,10s10-4.48,10-10S17.52,2,12,2z M12,20c-4.41,0-8-3.59-8-8s3.59-8,8-8s8,3.59,8,8 S16.41,20,12,20z"/><path d="M11,7h2v7h-2V7z M11,16h2v2h-2V16z"/></svg>');
            background-size: contain;
            background-repeat: no-repeat;
            z-index: 0;
        }
        
        .step-title {
            font-size: 1.8rem;
            margin-bottom: 20px;
            color: var(--secondary);
            position: relative;
            z-index: 1;
        }
        
        .step-content {
            position: relative;
            z-index: 1;
        }
        
        .terms-content {
            max-height: 400px;
            overflow-y: auto;
            padding: 15px;
            border: 1px solid var(--border);
            border-radius: 5px;
            background-color: rgba(255,255,255,0.8);
            margin-bottom: 20px;
            font-family: sans-serif;
            line-height: 1.5;
        }
        
        .terms-content h3 {
            margin-top: 0;
            color: var(--primary);
        }
        
        .terms-content p {
            margin-bottom: 15px;
        }
        
        .terms-checkbox {
            margin-bottom: 20px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: var(--text);
        }
        
        input[type="text"],
        input[type="password"],
        select {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid var(--border);
            border-radius: 5px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        input[type="text"]:focus,
        input[type="password"]:focus,
        select:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 2px rgba(255,107,139,0.2);
        }
        
        .btn {
            padding: 12px 24px;
            background-color: var(--primary);
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.2s;
            font-family: 'ZCOOL KuaiLe', cursive;
            display: inline-block;
        }
        
        .btn:hover {
            background-color: #ff4a70;
            transform: translateY(-2px);
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .btn-next {
            background-color: var(--secondary);
        }
        
        .btn-next:hover {
            background-color: #5ba8ff;
        }
        
        .btn-install {
            background-color: var(--success);
        }
        
        .btn-install:hover {
            background-color: #27ae60;
        }
        
        .error-message {
            background-color: var(--error);
            color: white;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        
        .success-message {
            background-color: var(--success);
            color: white;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        
        .installation-steps {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
            position: relative;
        }
        
        .installation-steps::before {
            content: '';
            position: absolute;
            top: 15px;
            left: 0;
            width: 100%;
            height: 4px;
            background-color: var(--border);
            z-index: 0;
        }
        
        .installation-steps::after {
            content: '';
            position: absolute;
            top: 15px;
            left: 0;
            height: 4px;
            background-color: var(--primary);
            z-index: 1;
            <?php
            // 根据当前步骤设置进度条宽度
            switch ($_SESSION['install_step']) {
                case INSTALLATION_STEP['TERMS']:
                    echo 'width: 25%;';
                    break;
                case INSTALLATION_STEP['DB_CONFIG']:
                    echo 'width: 50%;';
                    break;
                case INSTALLATION_STEP['INSTALL']:
                    echo 'width: 75%;';
                    break;
                case INSTALLATION_STEP['COMPLETE']:
                    echo 'width: 100%;';
                    break;
            }
            ?>
        }
        
        .step {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: var(--border);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            position: relative;
            z-index: 2;
        }
        
        .step.active {
            background-color: var(--primary);
        }
        
        .step.completed {
            background-color: var(--success);
        }
        
        .step-label {
            position: absolute;
            bottom: -25px;
            left: 50%;
            transform: translateX(-50%);
            font-size: 12px;
            white-space: nowrap;
        }
        
        .installation-info {
            margin-top: 30px;
            padding: 20px;
            background-color: rgba(116,185,255,0.1);
            border-radius: 5px;
            border-left: 4px solid var(--secondary);
        }
        
        .installation-info h3 {
            margin-top: 0;
            color: var(--secondary);
        }
        
        .installation-info ul {
            padding-left: 20px;
            margin-bottom: 0;
        }
        
        .installation-info li {
            margin-bottom: 8px;
        }
        
        /* Language Switcher */
        .language-switcher {
            text-align: right;
            margin-bottom: 20px;
        }
        
        .language-switcher select {
            padding: 8px 12px;
            border-radius: 5px;
            border: 1px solid var(--border);
            background-color: var(--card-bg);
            color: var(--text);
            font-size: 14px;
        }
        
        /* 响应式设计 */
        @media screen and (max-width: 768px) {
            .container {
                padding: 15px;
            }
            
            .header h1 {
                font-size: 2rem;
            }
            
            .install-card {
                padding: 20px;
            }
            
            .step-label {
                font-size: 10px;
            }
            
            .language-switcher {
                text-align: center;
                margin-bottom: 15px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><?php echo $language->get('system_name'); ?></h1>
            <p><?php echo $language->get('install_guide'); ?></p>
        </div>
        
        <div class="installation-steps">
            <div class="step <?php if ($_SESSION['install_step'] >= INSTALLATION_STEP['TERMS']) echo 'completed'; ?>">1</div>
            <div class="step <?php if ($_SESSION['install_step'] >= INSTALLATION_STEP['DB_CONFIG']) echo 'completed'; ?><?php if ($_SESSION['install_step'] === INSTALLATION_STEP['DB_CONFIG']) echo ' active'; ?>">2</div>
            <div class="step <?php if ($_SESSION['install_step'] >= INSTALLATION_STEP['INSTALL']) echo 'completed'; ?><?php if ($_SESSION['install_step'] === INSTALLATION_STEP['INSTALL']) echo ' active'; ?>">3</div>
            <div class="step <?php if ($_SESSION['install_step'] >= INSTALLATION_STEP['COMPLETE']) echo 'completed'; ?><?php if ($_SESSION['install_step'] === INSTALLATION_STEP['COMPLETE']) echo ' active'; ?>">4</div>
        </div>
        
        <!-- Language Switcher -->
        <div class="language-switcher">
            <form method="get" style="display: inline;">
                <select name="lang" onchange="this.form.submit()">
                    <?php 
                    $languages = $language->getLanguageOptions();
                    $currentLang = $language->getCurrentLanguage();
                    foreach ($languages as $code => $name) {
                        echo '<option value="' . $code . '"' . ($code === $currentLang ? ' selected' : '') . '>' . $name . '</option>';
                    }
                    ?>
                </select>
            </form>
        </div>
        
        <div class="install-card">
            <?php if ($_SESSION['install_step'] === INSTALLATION_STEP['TERMS']): ?>
                <h2 class="step-title"><?php echo $language->get('step_terms'); ?></h2>
                <div class="step-content">
                    <?php if (isset($error)): ?>
                        <div class="error-message"><?php 
                        if (strpos($error, '数据库连接失败') === 0) {
                            echo $language->get('error_db_connect') . substr($error, strlen('数据库连接失败: '));
                        } elseif (strpos($error, '安装失败') === 0) {
                            echo $language->get('error_install') . substr($error, strlen('安装失败: '));
                        } elseif (strpos($error, '系统错误') === 0) {
                            echo $language->get('error_system') . substr($error, strlen('系统错误: '));
                        } else {
                            echo $error;
                        }
                        ?></div>
                    <?php endif; ?>
                    
                    <div class="terms-content">
                        <h3><?php echo $language->get('terms_content_title'); ?></h3>
                        <p><?php echo $language->get('terms_welcome'); ?></p>
                        
                        <h3><?php echo $language->get('terms_definition'); ?></h3>
                        <p><?php echo $language->get('terms_definition_system'); ?></p>
                        <p><?php echo $language->get('terms_definition_user'); ?></p>
                        
                        <h3><?php echo $language->get('terms_license'); ?></h3>
                        <p><?php echo $language->get('terms_license_desc'); ?></p>
                        <p><?php echo $language->get('terms_license_condition'); ?></p>
         

                        <h3><?php echo $language->get('terms_author'); ?></h3>
                        <p><?php echo $language->get('terms_author_desc'); ?> <a href="https://space.bilibili.com/701864046" target="_blank">松坂有希</a>。</p>
                        <p>Author: <a href="https://space.bilibili.com/701864046" target="_blank">Matsuzaka Yuki</a>.</p>

                        <h3><?php echo $language->get('terms_obligation'); ?></h3>
                        <p><?php echo $language->get('terms_obligation_1'); ?></p>
                        <p><?php echo $language->get('terms_obligation_2'); ?></p>
                        <p><?php echo $language->get('terms_obligation_3'); ?></p>
                        
                        <h3><?php echo $language->get('terms_ip'); ?></h3>
                        <p><?php echo $language->get('terms_ip_desc'); ?></p>
                        
                        <h3><?php echo $language->get('terms_disclaimer'); ?></h3>
                        <p><?php echo $language->get('terms_disclaimer_desc'); ?></p>
                        
                        <h3><?php echo $language->get('terms_modification'); ?></h3>
                        <p><?php echo $language->get('terms_modification_desc'); ?></p>
                    </div>
                    
                    <form method="POST" action="index.php">
                        <div class="terms-checkbox">
                        <input type="checkbox" id="agree_terms" name="agree_terms" required>
                        <label for="agree_terms"><?php echo $language->get('terms_agree'); ?></label>
                    </div>
                    
                    <button type="submit" class="btn btn-next"><?php echo $language->get('terms_next'); ?></button>
                    </form>
                </div>
            <?php elseif ($_SESSION['install_step'] === INSTALLATION_STEP['DB_CONFIG']): ?>
                <h2 class="step-title"><?php echo $language->get('step_db_config'); ?></h2>
                <div class="step-content">
                    <?php if (isset($error)): ?>
                        <div class="error-message"><?php 
                        if (strpos($error, '数据库连接失败') === 0) {
                            echo $language->get('error_db_connect') . substr($error, strlen('数据库连接失败: '));
                        } elseif (strpos($error, '安装失败') === 0) {
                            echo $language->get('error_install') . substr($error, strlen('安装失败: '));
                        } elseif (strpos($error, '系统错误') === 0) {
                            echo $language->get('error_system') . substr($error, strlen('系统错误: '));
                        } else {
                            echo $error;
                        }
                        ?></div>
                    <?php endif; ?>
                    
                    <form method="POST" action="index.php">
                        <div class="form-group">
                            <label for="db_host"><?php echo $language->get('db_host'); ?></label>
                            <input type="text" id="db_host" name="db_host" value="localhost" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="db_port"><?php echo $language->get('db_port'); ?></label>
                            <input type="text" id="db_port" name="db_port" value="3306" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="db_name"><?php echo $language->get('db_name'); ?></label>
                            <input type="text" id="db_name" name="db_name" placeholder="<?php echo $language->get('db_name'); ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="db_user"><?php echo $language->get('db_user'); ?></label>
                            <input type="text" id="db_user" name="db_user" placeholder="<?php echo $language->get('db_user'); ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="db_pass"><?php echo $language->get('db_pass'); ?></label>
                            <input type="password" id="db_pass" name="db_pass" placeholder="<?php echo $language->get('db_pass'); ?>">
                        </div>
                        
                        <button type="submit" class="btn btn-next"><?php echo $language->get('db_test_connect'); ?></button>
                    </form>
                </div>
            <?php elseif ($_SESSION['install_step'] === INSTALLATION_STEP['INSTALL']): ?>
                <h2 class="step-title"><?php echo $language->get('step_install'); ?></h2>
                <div class="step-content">
                    <?php if (isset($error)): ?>
                        <div class="error-message"><?php echo $error; ?></div>
                        <form method="POST" action="index.php">
                            <button type="submit" class="btn btn-install"><?php echo $language->get('install_retry'); ?></button>
                        </form>
                    <?php else: ?>
                        <p><?php echo $language->get('install_progress'); ?></p>
                        <form method="POST" action="index.php">
                            <button type="submit" class="btn btn-install"><?php echo $language->get('install_start'); ?></button>
                        </form>
                    <?php endif; ?>
                </div>
            <?php elseif ($_SESSION['install_step'] === INSTALLATION_STEP['COMPLETE']): ?>
                <h2 class="step-title"><?php echo $language->get('step_complete'); ?></h2>
                <div class="step-content">
                    <div class="success-message"><?php echo $language->get('complete_success'); ?></div>
                    
                    <div class="installation-info">
                        <h3><?php echo $language->get('complete_info'); ?></h3>
                        <ul>
                            <li><?php echo $language->get('complete_admin_account'); ?>: <strong>admin</strong></li>
                            <li><?php echo $language->get('complete_initial_password'); ?>: <strong>admin123</strong><?php echo $language->get('complete_change_password'); ?></li>
                            <li><?php echo $language->get('complete_admin_url'); ?>: <a href="../admin/index.php"><?php echo $language->get('complete_enter_admin'); ?></a></li>
                        </ul>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>